<?php

namespace app\api\controller;

use app\common\controller\Api;

use think\Db;


/**
 * 会员接口
 */
class Question extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    /*
     * 问卷调查
     * */
    public function getQuestion()
    {
        $uid = $this->auth->id;
        $list = Db::table('keep_questionnaire')
            ->where('status', 0)
            ->where('deletetime',null)
            ->order('weigh', 'desc')
            ->order('id', 'desc')
            //->field('createtime, weigh, updatetime, deletetime, status', true)
            ->field('id,title, ext, type')
            ->select()
            ->toArray();
        if ($list) {
            foreach ($list as &$v) {
                if ($v['type'] != 2) {
                    $temp = Db::table('keep_questionnaire')
                        ->where('id', $v['id'])
                        ->field('id,title, ext, type,createtime, weigh, updatetime, deletetime, status', true)
                        ->find();
                    foreach ($temp as $k => $val) {
                        if ($val) {
                            $v['choice'][] = $val;
                        }
                    }
                }
            }
        }
        $data['list'] = $list;
        $questionnaire = Db::name('user_questionnaire')->where('user_id', $uid)->find();
        if ($questionnaire) {
            $data['exist'] = true;
        } else {
            $data['exist'] = false;
        }
        $this->success('问卷列表', $data);
    }

    /*
     *
     * 保存问卷
     * */
    public function save()
    {
        $data = file_get_contents("php://input");

        $data = json_decode($data,'true');
        $uid = $this->auth->id;
        foreach ($data as &$v) {
            $question = Db::table('keep_questionnaire')->where('id', $v['id'])->find();
            $v['titile'] = $question['title'];
            $v['ext_title'] = $question['ext'];
            $v['type'] = $question['type'];

        }
        $venue_id = Db::table('keep_user')->where('id', $uid)->value('venue_id');
        DB::name('user_questionnaire')->insert(['user_id' => $uid, 'venue_id' => $venue_id, 'content' => json_encode($data), 'ctime' => time()]);
        $this->success('保存成功');
    }
}
